package com.example.fw;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import com.gargoylesoftware.htmlunit.ThreadedRefreshHandler;
import com.gargoylesoftware.htmlunit.WaitingRefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class AdminHelper extends HelperBase{

	private WebClient webClient;
	private String baseUrl;

	public AdminHelper(ApplicationManager manager) {
		super(manager);
		webClient = new WebClient();
		webClient.setRefreshHandler(new ThreadedRefreshHandler());
		baseUrl = manager.getProperty("baseURL");
	}

	public boolean userExists(User user) throws Exception {
		HtmlPage userPage = openUserPage(user, baseUrl);
		HtmlForm deleteForm = findUserRemovalForm(userPage);
		return deleteForm != null;
	}

	public void deleteUserIfExists(User user) throws Exception {
		HtmlPage userPage = openUserPage(user, baseUrl);
		HtmlForm deleteForm = findUserRemovalForm(userPage);
		if ( deleteForm != null ){
			HtmlPage commitPage = (HtmlPage) deleteForm.getInputByValue("Delete User").click();
			HtmlForm commitForm = findUserRemovalForm(commitPage);
			commitForm.getInputByValue("Delete Account").click();
		}
	}

	private HtmlPage openUserPage(User user, String baseUrl)
			throws IOException, MalformedURLException {
		loginAdminIfRequared();
		String userId = manager.getHibernateHelper().getUserId(user.login);
		HtmlPage userPage = (HtmlPage)webClient.getPage(baseUrl+"manage_user_edit_page.php?user_id="+ userId);
		return userPage;
	}

	private void loginAdminIfRequared() throws IOException, MalformedURLException {
		String adminLogin = manager.getProperty("admin.login");
		String adminPass = manager.getProperty("admin.pass");
	
		HtmlPage mainPage = (HtmlPage)webClient.getPage(baseUrl);
		HtmlForm loginForm = mainPage.getFormByName("login_form");
		if ( loginForm != null ){
			loginForm.getInputByName("username").setValueAttribute(adminLogin);
			loginForm.getInputByName("password").setValueAttribute(adminPass);
			loginForm.getInputByValue("Login").click();
		}
	}

	private HtmlForm findUserRemovalForm(HtmlPage userPage) {
		List<HtmlForm> forms = userPage.getForms();
		for(HtmlForm form : forms){
			if ( "manage_user_delete.php".equals(form.getActionAttribute()) ){
				 return form;
			}
		}
		return null;
	}
}
